"""
日志配置模块 - 管理日志格式和输出

此模块包含日志过滤器、格式化器和美化输出功能。
"""

import logging
import sys
import uvicorn
import os
from logging.handlers import RotatingFileHandler


# 创建过滤器来阻止包含特定字符串的日志消息
class MessageFilter(logging.Filter):
    def filter(self, record):
        # 阻止包含这些字符串的消息
        blocked_phrases = [
            "LiteLLM completion()",
            "HTTP Request:", 
            "selected model name for cost calculation",
            "utils.py",
            "cost_calculator"
        ]
        
        if hasattr(record, 'msg') and isinstance(record.msg, str):
            for phrase in blocked_phrases:
                if phrase in record.msg:
                    return False
        return True


# 模型映射日志的自定义格式化器
class ColorizedFormatter(logging.Formatter):
    """用于突出显示模型映射的自定义格式化器"""
    BLUE = "\033[94m"
    GREEN = "\033[92m"
    YELLOW = "\033[93m"
    RED = "\033[91m"
    RESET = "\033[0m"
    BOLD = "\033[1m"
    
    def format(self, record):
        if record.levelno == logging.debug and "MODEL MAPPING" in record.msg:
            # 对模型映射日志应用颜色和格式
            return f"{self.BOLD}{self.GREEN}{record.msg}{self.RESET}"
        return super().format(record)


# 定义终端输出的 ANSI 颜色代码
class Colors:
    CYAN = "\033[96m"
    BLUE = "\033[94m"
    GREEN = "\033[92m"
    YELLOW = "\033[93m"
    RED = "\033[91m"
    MAGENTA = "\033[95m"
    RESET = "\033[0m"
    BOLD = "\033[1m"
    UNDERLINE = "\033[4m"
    DIM = "\033[2m"


def setup_logging():
    """设置日志配置"""
    # 确保 logs 目录存在
    os.makedirs("logs", exist_ok=True)
    
    # 配置根日志器
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.DEBUG)
    
    # 清除现有的处理器
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # 设置日志格式
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    
    # 文件处理器 - 写入到 logs/server.log，支持轮转
    file_handler = RotatingFileHandler(
        'logs/server.log',
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    
    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(ColorizedFormatter('%(asctime)s - %(levelname)s - %(message)s'))
    
    # 添加处理器到根日志器
    root_logger.addHandler(file_handler)
    root_logger.addHandler(console_handler)
    
    # 将过滤器应用到根日志器以捕获所有消息
    root_logger.addFilter(MessageFilter())

    # 配置 uvicorn 更安静
    # 让 uvicorn 的日志器保持安静
    logging.getLogger("uvicorn").setLevel(logging.WARNING)
    logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
    logging.getLogger("uvicorn.error").setLevel(logging.WARNING)
    
    logger = logging.getLogger(__name__)
    return logger


def log_request_beautifully(method, path, claude_model, openai_model, num_messages, num_tools, status_code):
    """以美观、Twitter 友好的格式记录请求，显示 Claude 到 OpenAI 的映射。"""
    # 优雅地格式化 Claude 模型名称
    claude_display = f"{Colors.CYAN}{claude_model}{Colors.RESET}"
    
    # 提取端点名称
    endpoint = path
    if "?" in endpoint:
        endpoint = endpoint.split("?")[0]
    
    # 仅提取没有提供商前缀的 OpenAI 模型名称
    openai_display = openai_model
    if "/" in openai_display:
        openai_display = openai_display.split("/")[-1]
    openai_display = f"{Colors.GREEN}{openai_display}{Colors.RESET}"
    
    # 格式化工具和消息
    tools_str = f"{Colors.MAGENTA}{num_tools} tools{Colors.RESET}"
    messages_str = f"{Colors.BLUE}{num_messages} messages{Colors.RESET}"
    
    # 格式化状态码
    status_str = f"{Colors.GREEN}✓ {status_code} OK{Colors.RESET}" if status_code == 200 else f"{Colors.RED}✗ {status_code}{Colors.RESET}"
    

    # 以清晰、美观的格式将所有内容组合在一起
    log_line = f"{Colors.BOLD}{method} {endpoint}{Colors.RESET} {status_str}"
    model_line = f"{claude_display} → {openai_display} {tools_str} {messages_str}"
    
    # 打印到控制台
    print(log_line)
    print(model_line)
    sys.stdout.flush()